<?php
class AdminController extends Controller
{
	public function init()
	{
		parent::init();
		/*check if logined*/
		if (Yii::app()->user->isGuest){
			$this->redirect(Yii::app()->createUrl('auth/login', array('url'=>urlencode(Utils::getCurrentUrl()))));
		}
	}
	
	public function checkPermission($action){
		$error = false;
		/*check if has permission*/
		if(in_array($action, array('deparments', 'subjects', 'folders', 'mailer'))){
			if(!Yii::app()->user->hasPermission('helpdesk-manage-settings')) $error = true;
		}
		else if(in_array($action, array('users', 'permissions'))){
			if(!Yii::app()->user->hasPermission('helpdesk-manage-users')) $error = true;
		}
		else if(in_array($action, array('documents', 'faqs'))){
			if(!Yii::app()->user->hasPermission('helpdesk-manage-contents')) $error = true;
		}
		if($error == true){
			$this->redirect('/error.html');	
		}
	}
	
	public function actionIndex()
	{
		$this->render('index');
	}
	
	public function actionDepartments()
	{
		$this->checkPermission(Yii::app()->controller->action->id);
		
		$intId = Yii::app()->request->getParam('id', null);
		
		//delete
		$action = Yii::app()->request->getParam('act', null);
		if(!empty($intId) && $action == 'delete'){
			try{
				$result = Categories::getInstance()->delete($intId);
				HelpDesk::getInstance()->removeCategory($intId);
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', "Delete subjects & tickets first!");
			}
			$this->redirect('/admin/departments');
		}
		
		//insert / update
		if(Yii::app()->request->isPostRequest)
		{
			/*get dept section*/
			$dept = Categories::getInstance()->get('helpdesk-departments');
			if(empty($dept)) die('Function has not been installed yet!');
			$args = array(		
				'category_code' => 'helpdesk'.'-'.time().'::'.Utils::uri_encode(Yii::app()->request->getParam('category_name', null)),		
				'category_name' => Yii::app()->request->getParam('category_name', null),
				'category_parent' => $dept['category_id'],
				'category_status' => 1
			);
			if(empty($intId))
				$result = Categories::getInstance()->insert($args);
			else
				$result = Categories::getInstance()->update($intId, $args);
			Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			$this->redirect('/admin/departments');
		}
		
		/*load depts.*/
		$arrDepts = HelpDesk::getInstance()->getDepts();
		
		/*dept detail*/
		$department = array();
		if(!empty($intId)){
			$department = Categories::getInstance()->get($intId);
		}
		
		$this->render('departments', array(
			'arrDepts' => $arrDepts,
			'department' => $department,
			'intId' => $intId
		));	
	}
	
	public function actionSubjects()
	{
		$this->checkPermission(Yii::app()->controller->action->id);
		
		$intDeptId = Yii::app()->request->getParam('dept', null);
		$intId = Yii::app()->request->getParam('id', null);
		
		//delete
		$action = Yii::app()->request->getParam('act', null);
		if(!empty($intId) && $action == 'delete'){
			try{
				$result = Categories::getInstance()->delete($intId);
				HelpDesk::getInstance()->removeCategory($intId);
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', "Delete subjects & tickets first!");
			}
			$this->redirect('/admin/subjects/?dept='.$intDeptId);
		}
		
		//insert / update
		if(Yii::app()->request->isPostRequest)
		{
			if(empty($intDeptId)) $this->redirect('/admin/subjects');
			$args = array(		
				'category_code' => 'helpdesk'.'-'.time().'::'.Utils::uri_encode(Yii::app()->request->getParam('category_name', null)),		
				'category_name' => Yii::app()->request->getParam('category_name', null),
				'category_parent' => $intDeptId,
				'category_status' => 1
			);
			if(empty($intId))
				$result = Categories::getInstance()->insert($args);
			else
				$result = Categories::getInstance()->update($intId, $args);
			Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			$this->redirect(array('/admin/subjects/', 'dept'=>$intDeptId));
		}
		
		/*load depts.*/
		$arrDepts = HelpDesk::getInstance()->getDepts();

		if(empty($intDeptId)){
			if(!empty($arrDepts)){
				$this->redirect(array('/admin/subjects/', 'dept'=>$arrDepts[0]['category_id']));
			} else {
				Yii::app()->user->setFlash('error', "Cannot create subject, you have to define department first!");	
			}
		}
		
		/*load subjects*/
		$arrSubjects = HelpDesk::getInstance()->getSubjects($intDeptId);
		
		/*subject detail*/
		$subject = array();
		if(!empty($intId)){
			$subject = Categories::getInstance()->get($intId);
		}
		
		$this->render('subjects', array(
			'arrDepts' => $arrDepts,
			'arrSubjects' => $arrSubjects,
			'subject' => $subject,
			'intDeptId' => $intDeptId,
			'intId' => $intId
		));
	}
	
	public function actionDocumentFolders()
	{
		$this->checkPermission(Yii::app()->controller->action->id);

		$intId = Yii::app()->request->getParam('id', null);
		
		//delete
		$action = Yii::app()->request->getParam('act', null);
		if(!empty($intId) && $action == 'delete'){
			try{
				$result = Categories::getInstance()->delete($intId);
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', Yii::t('helpdesk', "Delete subfolders and documents in this folder first!"));
			}
			$this->redirect('/admin/documentfolders');
		}
		
		//insert / update
		if(Yii::app()->request->isPostRequest)
		{
			try{
				/*get folder section*/
				$folder = Categories::getInstance()->get('helpdesk-documents');
				$parent = Yii::app()->request->getParam('parent', null);
				if(empty($folder)) die('Function has not been installed yet!');	
				$args = array(		
					'category_code' => 'helpdesk'.'-'.time().'::'.Utils::uri_encode(Yii::app()->request->getParam('category_name', null)),		
					'category_name' => Yii::app()->request->getParam('category_name', null),
					'category_parent' => empty($parent)?$folder['category_id']:$parent,
					'category_status' => 1
				);
				if(empty($intId))
					$result = Categories::getInstance()->insert($args);
				else
					$result = Categories::getInstance()->update($intId, $args);
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', Yii::t('helpdesk', 'An error occured, please contact your admin'));
			}
			$this->redirect('/admin/documentfolders');
		}
		
		/*load folders.*/
		$arrFolders = HelpDesk::getInstance()->getDocumentFolders(); //o($arrFolders);
		
		/*dept detail*/
		$folder = array();
		if(!empty($intId)){
			$folder = Categories::getInstance()->get($intId);
		}
		
		$this->render('document-folders', array(
			'arrFolders' => $arrFolders,
			'folder' => $folder,
			'intId' => $intId
		));	
	}
	
	public function actionFAQFolders()
	{
		$this->checkPermission(Yii::app()->controller->action->id);

		$intId = Yii::app()->request->getParam('id', null);
		
		//delete
		$action = Yii::app()->request->getParam('act', null);
		if(!empty($intId) && $action == 'delete'){
			try{
				$result = Categories::getInstance()->delete($intId);
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', "Delete documents in this folder first!");
			}
			$this->redirect('/admin/faqfolders');
		}
		
		//insert / update
		if(Yii::app()->request->isPostRequest)
		{
			try{
				/*get folder section*/
				$folder = Categories::getInstance()->get('helpdesk-faqs');
				$parent = Yii::app()->request->getParam('parent', null);
				if(empty($folder)) die('Function has not been installed yet!');	
				$args = array(		
					'category_code' => 'helpdesk'.'-'.time().'::'.Utils::uri_encode(Yii::app()->request->getParam('category_name', null)),		
					'category_name' => Yii::app()->request->getParam('category_name', null),
					'category_parent' => empty($parent)?$folder['category_id']:$parent,
					'category_status' => 1
				);
				if(empty($intId))
					$result = Categories::getInstance()->insert($args);
				else
					$result = Categories::getInstance()->update($intId, $args);
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', Yii::t('helpdesk', 'An error occured, please contact your admin'));
			}
			$this->redirect('/admin/faqfolders');
		}
		
		/*load folders.*/
		$arrFolders = HelpDesk::getInstance()->getFAQFolders();
		
		/*dept detail*/
		$folder = array();
		if(!empty($intId)){
			$folder = Categories::getInstance()->get($intId);
		}
		
		$this->render('faq-folders', array(
			'arrFolders' => $arrFolders,
			'folder' => $folder,
			'intId' => $intId
		));	
	}
	
	public function actionFAQs()
	{
		$this->checkPermission(Yii::app()->controller->action->id);
		
		/*get list folders*/
		$arrFolders = HelpDesk::getInstance()->getFAQFolders();
		
		$intId = Yii::app()->request->getParam('id', null);
		$renderType = Yii::app()->request->getParam('render', null);
		if($renderType == 'form'){
			if(Yii::app()->request->isPostRequest)
			{
				$args = array(
					'taxonomy_id' => 3,
					'post_title' => Yii::app()->request->getParam('title', null),
					'post_body' => Yii::app()->request->getParam('body', null),
					'post_status' => 1
				);	
				
				try{
					if(empty($intId)){
						//create ticket
						$args['post_creator_id'] = Yii::app()->user->id;
						$intId = $intResult = Posts::getInstance()->insert($args);
					} else{
						//update
						$args['post_last_modifier_id'] = Yii::app()->user->id;	
						$intResult = Posts::getInstance()->update($intId, $args);
					}
					if($intResult > 0){
						//udpate category
						$arrCategoryIds = Yii::app()->request->getParam('folder', null);
						if(!empty($arrCategoryIds)){
							Posts::getInstance()->updateCategory($intId, $arrCategoryIds);
						}
					}
					//done
					Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
					//$this->refresh();
					$this->redirect('/admin/faqs');
				} catch(Exception $ex){
					Yii::app()->user->setFlash('error', $ex->getMessage());
				}
			}		
			$faq = array();
			if(!empty($intId)){
				$faq = Posts::getInstance()->get($intId);
				//explode folders
				if(!empty($faq['post_category_id'])) $faq['post_category_id'] = explode(',', $faq['post_category_id']);
				//prevent faked id
				if($faq['taxonomy_id'] != 3) $this->redirect('/admin/faqs');
			}
			$this->render('faqs-form', array(
				'faq' => $faq,
				'intId' => $intId,
				'arrFolders' => $arrFolders
			));
		} else {
			//delete
			$action = Yii::app()->request->getParam('act', null);
			if(!empty($intId) && $action == 'delete'){
				try{
					$result = Posts::getInstance()->delete($intId);
					Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
				} catch(Exception $ex){
					Yii::app()->user->setFlash('error', $ex->getMessage());
				}
				$this->redirect('/admin/faqs');
			}
			$arrFilter = array(
				'folder' => Yii::app()->request->getParam('folder', null)
			);
			/* get list*/
			$intRowsPerPage = DEFAULT_ROWS_PER_PAGE;
			$intPage = Yii::app()->request->getParam('page', 1);
			$arrFaqs = Posts::getInstance()->getList(array(
				'taxonomy_id' => 3,
				'post_status' => 1,	
				'category_id' => $arrFilter['folder'],				
				'page' => $intPage,
				'limit' => $intRowsPerPage,
			));
			$intTotalRows = isset($arrFaqs[0]['total_rows'])?$arrFaqs[0]['total_rows']:0;
			//paging
			$objPages=new CPagination($intTotalRows);
			$objPages->setCurrentPage($intPage-1);
			$objPages->setPageSize($intRowsPerPage);
			$this->render('faqs', array(
				'arrFaqs' => $arrFaqs, 
				'arrFolders' => $arrFolders,
				'objPages' => $objPages,
				'arrFilter' => $arrFilter,
			));	
		}
	}
	
	public function actionDocuments()
	{
		$this->checkPermission(Yii::app()->controller->action->id);
		
		/*get list folders*/
		$arrFolders = HelpDesk::getInstance()->getDocumentFolders();
				
		$intId = Yii::app()->request->getParam('id', null);
		$renderType = Yii::app()->request->getParam('render', null);
		if($renderType == 'form'){
			if(Yii::app()->request->isPostRequest)
			{
				$args = array(
					'taxonomy_id' => 2,
					'post_title' => Yii::app()->request->getParam('title', null),
					'post_body' => Yii::app()->request->getParam('body', null),
					'post_privacy' => Yii::app()->request->getParam('privacy', null), //allow download
					'post_status' => Yii::app()->request->getParam('status', null)
				);	
				
				try{
					if(empty($intId)){
						//create document
						$args['post_creator_id'] = Yii::app()->user->id;
						$intId = $intResult = Posts::getInstance()->insert($args);
						if($intId > 0){
							//upload attachments
							if($_FILES['attach']['error'] == UPLOAD_ERR_OK){						
								$path = $this->uploadAttachment($_FILES['attach']);
								$attachField = Posts::getInstance()->getFieldByName('article-attachment');
								Posts::getInstance()->updateField($intId, $attachField['field_id'], $path);
							}
						}
					} else{
						//update
						$args['post_last_modifier_id'] = Yii::app()->user->id;	
						Posts::getInstance()->update($intId, $args);
						$intResult = 1;
						if($intResult > 0){							
							//update attachments
							if($_FILES['attach']['error'] == UPLOAD_ERR_OK){								
								//retrieve and delete old attachment
								$document = Posts::getInstance()->get($intId);
								if(isset($document['fields']['article-attachment'])){
									$this->removeAttachment($document['fields']['article-attachment']);	
								}
												
								//update new attachment
								$path = $this->uploadAttachment($_FILES['attach']);
								$attachField = Posts::getInstance()->getFieldByName('article-attachment');
								Posts::getInstance()->updateField($intId, $attachField['field_id'], $path);
							}
						}
					}
					
					if($intResult > 0){
						//udpate category
						$arrCategoryIds = Yii::app()->request->getParam('folder', null);
						if(!empty($arrCategoryIds)){
							Posts::getInstance()->updateCategory($intId, $arrCategoryIds);
						}
					}
					//done
					Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
					//$this->refresh();
					$this->redirect('/admin/documents');
				} catch(Exception $ex){
					Yii::app()->user->setFlash('error', $ex->getMessage());
				}
			}	
			$document = array();
			if(!empty($intId)){
				$document = Posts::getInstance()->get($intId);
				//explode folders
				if(!empty($document['post_category_id'])) $document['post_category_id'] = explode(',', $document['post_category_id']);
				//prevent faked id
				if($document['taxonomy_id'] != 2) $this->redirect('/admin/documents');
			}
			$this->render('documents-form', array(
				'arrFolders' => $arrFolders,
				'document' => $document,
				'intId' => $intId
			));
		} else {
			//delete
			$action = Yii::app()->request->getParam('act', null);
			if(!empty($intId) && $action == 'delete'){
				try{
					//retrieve and delete old attachment
					$document = Posts::getInstance()->get($intId);
					if(isset($document['fields']['article-attachment'])){
						$this->removeAttachment($document['fields']['article-attachment']);	
					}
					//remove document from db
					$result = Posts::getInstance()->delete($intId);					
					Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
				} catch(Exception $ex){
					Yii::app()->user->setFlash('error', $ex->getMessage());
				}
				$this->redirect('/admin/documents');
			}
			$arrFilter = array(
				'folder' => Yii::app()->request->getParam('folder', null)
			);
			/* get list*/
			$intRowsPerPage = DEFAULT_ROWS_PER_PAGE;
			$intPage = Yii::app()->request->getParam('page', 1);
			$arrDocuments = Posts::getInstance()->getList(array(
				'taxonomy_id' => 2,
				'post_status' => null, //get all status	
				'category_id' => $arrFilter['folder'],		
				'page' => $intPage,
				'limit' => $intRowsPerPage,
			));
			$intTotalRows = isset($arrDocuments[0]['total_rows'])?$arrDocuments[0]['total_rows']:0;
			//paging
			$objPages=new CPagination($intTotalRows);
			$objPages->setCurrentPage($intPage-1);
			$objPages->setPageSize($intRowsPerPage);
			$this->render('documents', array(
				'arrFolders' => $arrFolders,
				'arrDocuments' => $arrDocuments,
				'arrFilter' => $arrFilter,
				'objPages' => $objPages			
			));	
		}
	}
	
	public function actionUsers(){
		$this->checkPermission(Yii::app()->controller->action->id);		
		
		$userId = Yii::app()->request->getParam('id', null);
		if(!empty($userId)){
			$this->forward('admin/useredit'); exit;
		}
		
		/*detect role*/
		$role = Yii::app()->request->getParam('role', 1);
		if($role == 'members') $roleId = 3;
		else if($role == 'staffs') $roleId = '1,2';
		else $roleId = '1,2,3';
		
		//get params
		$intPage 		= Yii::app()->request->getParam('page', 1);
		$intRowsPerPage = DEFAULT_ROWS_PER_PAGE;
		$arrFilter = array(
			'user' => Yii::app()->request->getParam('user', null)==''?null:Yii::app()->request->getParam('user', null)
		);
		
		//load users
		$arrUsers = Users::getInstance()->getList(array(
			'role_id' => $roleId, 
			'user_status' => 1, 
			'keyword' => '%'.$arrFilter['user'].'%',
			'includeProfile' => true,
			'page' => $intPage,
			'limit' => $intRowsPerPage));
		$intTotalRows = isset($arrUsers[0]['total_rows'])?$arrUsers[0]['total_rows']:0;
		
		//pagination
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		
		$this->render('users', array(
			'arrUsers' => $arrUsers,
			'objPages' => $objPages,
			'role' => $role,
			'arrFilter' => $arrFilter
		));
		
		//history
		$_SESSION['history'] = Utils::getCurrentUrl();
	}
	
	public function actionUserEdit(){
		$this->checkPermission(Yii::app()->controller->action->id);
		
		//set redirect url
		if(!isset($_SESSION['history'])) $_SESSION['history'] = '/admin/members';
		
		/*detect role*/
		$role = Yii::app()->request->getParam('role');		
		
		/*load users info*/
		$userId = Yii::app()->request->getParam('id', null);
		$user = Users::getInstance()->get($userId);
		//don't allow edit supper admin
		if(is_array($user['roles']) && in_array('1', $user['roles']) && $user['user_id'] != Yii::app()->user->id){
			$this->redirect('/error.html');	
		}
		
		//delete user
		$userId = Yii::app()->request->getParam('id', null);
		$action = Yii::app()->request->getParam('act', null);
		if(!empty($userId) && $action == 'delete'){
			try{				
				$result = Users::getInstance()->delete($userId);
				HelpDesk::getInstance()->removeModerator($userId);							
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			} catch(Exception $ex){
				Yii::app()->user->setFlash('error', $ex->getMessage());
			}
			$this->redirect($_SESSION['history']);
		}
		
		//update user info
		if(Yii::app()->request->isPostRequest)
		{
			$args = Yii::app()->request->getParam('user', null);
			$args['user_username'] = $args['user_email'];
			$userId = Yii::app()->request->getParam('user_id', null);
			try{
				//check if input is valid
				if(empty($args['user_email']) || !filter_var($args['user_email'], FILTER_VALIDATE_EMAIL)){
					throw new Exception(Yii::t('helpdesk','Invalid data'));
				}
				
				$intResult = Users::getInstance()->update($userId, $args);
				
				//update profile
				$hasProfile = true;
				$profile = Users::getInstance()->getProfile($userId);
				if(empty($profile)){
					$hasProfile = false;	
				}
				$profile['profile_email'] = $args['user_username'];
				$profile['profile_phone'] = trim(Yii::app()->request->getPost('phone', null));
				$profile['profile_address'] = trim(Yii::app()->request->getPost('address', null));
				$profile['profile_allow_notify'] = Yii::app()->request->getParam('notification', null);
				$profile['profile_status'] = 1;
				if(!$hasProfile){
					Users::getInstance()->insertProfile($userId, $profile);
				} else {
					Users::getInstance()->updateProfile($userId, $profile);
				}
				
				//update password
				$password = Yii::app()->request->getParam('user_password', null);
				if($password != ''){
					Users::getInstance()->updatePassword($userId, $password);
				}
				
				//update role
				$roleId = Yii::app()->request->getParam('user_role', null);
				if(!empty($roleId)){
					Roles::getInstance()->updateUserRole($userId, $roleId);
				}
				
				//update user cate (STAFFS ONLY)
				$cats = Yii::app()->request->getParam('cats', null);
				if(!empty($cats)){
					HelpDesk::getInstance()->updateModeratorCategories($userId, $cats);					
				}
				
				//done
				Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
				
				//redirect
				$this->redirect($_SESSION['history']);
				//$this->refresh();
			} catch(Exception $ex){
					Yii::app()->user->setFlash('error', Yii::t('helpdesk', 'Sorry, this email already exists. Please choose another one or login to continue'));
					//Yii::app()->user->setFlash('error', $ex->getMessage());
			}
		}
		
		/*load users info*/
		$userId = Yii::app()->request->getParam('id', null);
		$user = Users::getInstance()->get($userId);
		if(!empty($user)){
			//load roles
			$roles = Roles::getInstance()->getUserRoles($userId);
			$roleIds = array();
			foreach($roles as $R){
				$roleIds[] = $R['role_id'];
			}
			$user['roles'] = implode($roleIds);
			//load user cate
			$user['category_id'] = HelpDesk::getInstance()->getModeratorCategories($userId);;
		}
		$profile = Users::getInstance()->getProfile($userId);
		
		/*load depts.*/
		$arrDepts = HelpDesk::getInstance()->getDepts(true);
		
		$this->render('users-form', array(
			'arrDepts' => $arrDepts,
			'user' => $user,
			'role' => $role,
			'profile' => $profile
		));
	}
	
	public function actionMailer(){
		$this->checkPermission(Yii::app()->controller->action->id);
		//update
		if(Yii::app()->request->isPostRequest)
		{
			$arrParams = Yii::app()->request->getParam('settings', null);
			foreach($arrParams as $code=>$value){
				Settings::getInstance()->update($code, $value);
			}
			Yii::app()->user->setFlash('ok', 'Update successfully');
		}
		//load mail settings
		$arrMailSettings  = Settings::getInstance()->getList(array('setting_group'=>'mail'), RETURN_KEY_VALUE_ARRAY);
		$this->render('mailer', array(
			'arrMailSettings' => $arrMailSettings
		));	
	}
	
	public function actionPermissions(){
		$this->checkPermission(Yii::app()->controller->action->id);
		
		$roleId = 2; //staffs
		//load role's permissions
		$arrPermissions = Permissions::getInstance()->getRolePermissions($roleId, 'helpdesk');
		if(Yii::app()->request->isPostRequest)
		{
			$arrCustomPermissions = Yii::app()->request->getParam('permission', array());
			$arrDefaultPermissions = array();
			foreach($arrPermissions as $R){
				array_push($arrDefaultPermissions, $R['permission_id']);	
			}
			$arrDefaultPermissions = array_fill_keys($arrDefaultPermissions, 0);
			$arrCustomPermissions = array_fill_keys($arrCustomPermissions, 1);
			//merge 2 array of custome and default role's permissions
			$arrCustomPermissions = $arrCustomPermissions+$arrDefaultPermissions;
			
			//update db
			Permissions::getInstance()->updateRolePermissions($roleId, $arrCustomPermissions);
			
			Yii::app()->user->setFlash('ok', Yii::t('helpdesk', 'Updated successfully!'));
			$this->refresh();
		}
		$this->render('permissions', array(
			'arrPermissions' => $arrPermissions
		));
	}
	
	public function actionDashboard(){
		$arrDeptStatistic = HelpDesk::getInstance()->getDeptStatistic();
		$arrSubjectStatistic = HelpDesk::getInstance()->getSubjectStatistic();
		$arrTemp = array();
		foreach($arrSubjectStatistic as $R){
			if(!empty($R['subject_id']))
				$arrTemp[$R['department_name']][] = $R;
			//else
				//$arrTemp[$R['department_name']] = array();
		}
		$arrSubjectStatistic = $arrTemp;
		$this->render('dashboard', array(
			'arrDeptStatistic' => $arrDeptStatistic,
			'arrSubjectStatistic' => $arrSubjectStatistic
		));
	}
	
	public function actionLogs(){
		
		$arrLogActions = array(
			'HELPDESK_LOGIN',
			'HELPDESK_CREATE_TICKET',
			'HELPDESK_REPLY_TICKET',
			'HELPDESK_CLOSE_TICKET',
			'HELPDESK_OPEN_TICKET',
			'HELPDESK_UPDATE_PROFILE',
			'HELPDESK_FORWARD_TICKET'
		);
		
		//get params
		$intRowsPerPage = 30; //DEFAULT_ROWS_PER_PAGE;
		$intPage = Yii::app()->request->getParam('page', 1);
		$arrFilters = array(
			'log_action' => (Yii::app()->request->getParam('action')=='')?null:Yii::app()->request->getParam('action'),
			'log_time' => array(
				'from' => (Yii::app()->request->getParam('dfrom')=='')?null:Yii::app()->request->getParam('dfrom'),
				'to' => (Yii::app()->request->getParam('dto')=='')?null:Yii::app()->request->getParam('dto')
			)
		);
		
		$args = $arrFilters;
		$args['log_time']['from'] = !empty($args['log_time']['from'])?date('Y-m-d', strtotime($args['log_time']['from'])):null;	
		$args['log_time']['to'] = !empty($args['log_time']['to'])?date('Y-m-d', strtotime($args['log_time']['to'])):null;
			
		//get logs
		$arrLogs = HelpDesk::getInstance()->getLogs($args, $intPage, $intRowsPerPage);
		$intTotalRows = isset($arrLogs[0]['total_rows'])?$arrLogs[0]['total_rows']:0;
		
		//paging
		$objPages=new CPagination($intTotalRows);
		$objPages->setCurrentPage($intPage-1);
		$objPages->setPageSize($intRowsPerPage);
		
		//render layout
		$this->render('logs', array(
			'arrLogActions' => $arrLogActions,
			'arrLogs' => $arrLogs,
			'objPages' => $objPages,
			'arrFilters' => $arrFilters
		));
	}
	
	private function uploadAttachment($file){
		try{
			/*start uploading...*/
			$objFileTransfer = new FileTransfer(UPLOADS_DIR, array('prefixPath'=>'src/'.date('Y').'/'.date('md')));
			$arrFileInfo = $objFileTransfer->upload($file, 0755, false);
			if($arrFileInfo !== false){
				/*prepare data for inserting db*/
				$args = array(
					'media_title' => $arrFileInfo['filename'],
					'media_file' => $arrFileInfo['path'],
					'media_file_size' => $arrFileInfo['size'],
					'media_file_extension' => $arrFileInfo['extension'],
					'media_src' => 1,
					'media_folder' => 'helpdesk-ticket',
					'media_creator_id' => Yii::app()->user->id
				);
				/*insert into database*/				
				Media::getInstance()->insert($args);
			}
			return isset($arrFileInfo['path'])?$arrFileInfo['path']:null;
		} catch(Exception $ex){
			Yii::app()->user->setFlash('error', $ex->getMessage());
		}
	}
	
	private function removeAttachment($filePath){
		try{
			$file = Media::getInstance()->getByPath($filePath);
			if(!empty($file) && is_file(UPLOADS_DIR.'/'.$file['media_file'])){
				//delete file
				if(!unlink(UPLOADS_DIR.'/'.$file['media_file'])) throw new Exception('Could not unlink file '.UPLOADS_DIR.'/'.$file['media_file']);
				//remove from db
				Media::getInstance()->delete($file['media_id']);
			}
		} catch(Exception $ex){
			Yii::app()->user->setFlash('error', $ex->getMessage());
		}
	}
}